# -*- coding = utf-8 -*-
# @Time : 2023/6/14 15:43
# @Author : 龙王赘婿_彪少
# @File : modbus_copy.py
# @Software: PyCharm

# 功能：供自己copy的模板

import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

PORT = "com1"
baudrate = 115200
ID = 0x01


class Modbus:
    def __init__(self):
        self.master = modbus_rtu.RtuMaster(
            serial.Serial(port=PORT, baudrate=baudrate, bytesize=8, parity='N', stopbits=1, xonxoff=0))
        self.master.set_timeout(1.0)

    # 读保持寄存器 0x03 用的最多
    def read_holding_resasters(self, addr, number):
        try:
            res = self.master.execute(ID, cst.READ_HOLDING_REGISTERS, starting_address=addr, quantity_of_x=number)
            print(res)
        except Exception as err:
            print("异常：", err)

    # 写单寄存器 0x06
    def write_single_register(self, addr, value):
        try:
            res = self.master.execute(ID, cst.WRITE_SINGLE_REGISTER, starting_address=addr, output_value=value)
            print(res)
        except Exception as err:
            print("异常：", err)


if __name__ == "__main__":
    m = Modbus()
    while True:
        key = input("输入指令：")
        # print(key, type(key))
        if key == "a":
            print("move")
        elif key == "b":
            print("stop")